#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 基础URL
BASE_URL="http://localhost:8000/api/v1"
TOKEN=""

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0

# 辅助函数
print_test_result() {
    local test_name=$1
    local result=$2
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if [ $result -eq 0 ]; then
        echo -e "${GREEN}✓ $test_name passed${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}✗ $test_name failed${NC}"
    fi
}

# 获取用户token
get_user_token() {
    response=$(curl -s -X POST "${BASE_URL}/user/login/" \
        -H "Content-Type: application/json" \
        -d '{
            "username": "analyst1",
            "password": "analyst123"
        }')
    
    TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['token'])")
}

# 1. 测试发送消息
test_send_message() {
    echo -e "\n${YELLOW}Testing Send Message...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/chat/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
            "message": "Hello, AI!",
            "context": [
                {
                    "type": "industry_report",
                    "id": "123",
                    "title": "示例报告"
                }
            ]
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Send Message" 0
    else
        print_test_result "Send Message" 1
    fi
}

# 2. 测试获取历史记录
test_get_history() {
    echo -e "\n${YELLOW}Testing Get History...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/chat/history/?page=1&pageSize=20" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Get History" 0
    else
        print_test_result "Get History" 1
    fi
}

# 3. 测试删除消息
test_delete_messages() {
    echo -e "\n${YELLOW}Testing Delete Messages...${NC}"
    
    response=$(curl -s -X DELETE "${BASE_URL}/chat/delete_history/" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Delete Messages" 0
    else
        print_test_result "Delete Messages" 1
    fi
}

# 4. 测试导出历史记录
test_export_history() {
    echo -e "\n${YELLOW}Testing Export History...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/chat/export/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
            "format": "pdf"
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Export History" 0
    else
        print_test_result "Export History" 1
    fi
}

# 5. 测试未授权访问
test_unauthorized_access() {
    echo -e "\n${YELLOW}Testing Unauthorized Access...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/chat/history/")
    
    echo "Response: $response"
    if [[ $response == *'"detail":"身份认证信息未提供。"'* ]]; then
        print_test_result "Unauthorized Access" 0
    else
        print_test_result "Unauthorized Access" 1
    fi
}

# 6. 测试无效消息格式
test_invalid_message() {
    echo -e "\n${YELLOW}Testing Invalid Message Format...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/chat/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d '{
            "content": "",
            "context": "invalid"
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":400'* ]]; then
        print_test_result "Invalid Message Format" 0
    else
        print_test_result "Invalid Message Format" 1
    fi
}

# 运行所有测试
run_all_tests() {
    echo -e "${YELLOW}Starting Chat API Tests...${NC}"
    
    # 获取token
    get_user_token
    
    # 运行测试
    test_send_message
    test_get_history
    test_delete_messages
    test_export_history
    test_unauthorized_access
    test_invalid_message
    
    echo -e "\n${YELLOW}Test Results:${NC}"
    echo -e "Total Tests: $TOTAL_TESTS"
    echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "Failed: ${RED}$((TOTAL_TESTS - PASSED_TESTS))${NC}"
}

# 执行测试
run_all_tests